package sealte.wdgf.control.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sealte.wdgf.model.pojo.Pet;
import sealte.wdgf.utils.UtilTools;

public class PetBean {
	
	private Connection conn;
	static Logger logger = LoggerFactory.getLogger(PetBean.class);
	
	public PetBean(Connection con){
		this.conn = con;
	}
	
	public List<Pet> getAll(){
		String sql = "SELECT name,color,age FROM T_PET ORDER BY name";
		Statement stmt = null;
		ResultSet rs = null;
		try{
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			logger.debug(sql);
			List<Pet> petList = new ArrayList<Pet>();
			while(rs.next()){
				Pet pet = new Pet();
				pet.setName(rs.getString(1));
				pet.setColor(rs.getString(2));
				pet.setAge(rs.getInt(3));
				petList.add(pet);
			}
			return petList;
		}catch(Exception ex){
			logger.error("查询全部T_PET内容时出错！原因："+ex.getMessage());
		}finally{
			UtilTools.closeStatementAndResultSet(stmt, rs);
		}
		return null;
	}
	
	public void add(Pet pet){
		String sql = "INSERT INTO T_PET(name,color,age) VALUES(?,?,?)";
		PreparedStatement ps = null;
		try{
			ps = conn.prepareStatement(sql);
			ps.setString(1, pet.getName());
			ps.setString(2, pet.getColor());
			ps.setInt(3, pet.getAge());
			logger.debug(sql);
			ps.executeUpdate();
		}catch(Exception ex){
			logger.error("插入新的Pet时出错！原因："+ex.getMessage());
		}finally{
			UtilTools.closeStatementAndResultSet(ps, null);
		}
	}
	
}
